using Microsoft.EntityFrameworkCore;
using vue0701.Domain.Common;
using vue0701.Domain.Entities;
using vue0701.Domain.Reposoitiories;
using vue0701.Infrastructure.Data;
namespace vue0701.Infrastructure.Reposoitiories;

public class EfRepository<T> : IRepository<T> where T : EntityBase
{   
    private readonly Vue0701DbContext _db;
    private readonly DbSet<T> _tb;
    public EfRepository(Vue0701DbContext db){
        _db=db;
        _tb=_db.Set<T>();
    }
    public async Task<T> CreateAsync(T entity)
    {
        var obj =await _tb.AddAsync(entity);
        await _db.SaveChangesAsync();
        return obj.Entity;
    }

    public async Task DeleteAsync(T entity)
    {
        // 硬删除
        // _tb.Remove(entity);
        // await _db.SaveChangesAsync();

        // 软删除
        entity.IsDeleted = true;
        await UpdateAsync(entity);
    }
    public async Task DeleteAsync(Guid id)
    {
        var obj = await GetByIdAsync(id);
        if (obj == null)
        {
            return;
        }
        await DeleteAsync(obj);
    }

 public async Task DeleteHardAsync(Guid id)
    {
        // 硬删除
        var obj = await GetByIdAsync(id);
        if (obj == null)
        {
            return;
        }
        _tb.Remove(obj);
        await _db.SaveChangesAsync();
    }

    public async Task<IEnumerable<T>> GetAllAsync()
    {
        var list = await _tb.AsNoTracking().ToListAsync();
        return list;
    }

    public async Task<T?> GetByIdAsync(Guid id)
    {
        var obj = await _tb.FindAsync(id);
        return obj;
    }
     public async Task<PagedResult<T>> GetPagedAsync(int pageIndex, int pageSize)
    {
        var list = await _tb.AsNoTracking()
        .Skip((pageIndex - 1) * pageSize)
        .Take(pageSize)
        .ToListAsync();

        var count = await _tb.CountAsync();

        var pagedResult = new PagedResult<T> { Items = list, TotalCount = count };

        return pagedResult;
    }

    public async Task UpdateAsync(T entity)
    {
        entity.UpdatedAt = DateTime.UtcNow;
        _tb.Update(entity);
        await _db.SaveChangesAsync();
    }

   
}
